<?php

namespace app\command;

use app\common\lib\Common;
use app\common\lib\RabbitMq;
use app\exception\IndexException;
use support\Container;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Webman\Event\Event;

class CronRabbitMq extends Command
{
    protected static $defaultName = 'cron:rabbitmq:queue';
    protected static $defaultDescription = 'cron rabbitmq queue';

    /**
     * @return void
     */
    protected function configure()
    {
        //发布执行结束
        Event::dispatch('console.start', []);

        $this->addArgument('queue', InputArgument::OPTIONAL, 'Name description');
        $this->addArgument('action', InputArgument::OPTIONAL, 'Action description');

        Common::initTaskConfig();
    }

    /**
     * 用户推广方案监听
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        try{
            $queue = $input->getArgument('queue');
            $action = $input->getArgument('action');

            $queues = array_filter(explode(',', $queue));

            $config = config('rabbitmq');

            foreach ($queues as $queueName){
                if(!isset($config['queue'][$queueName])){
                    throw new IndexException(4020,$queueName.'队列不存在');
                }

                if($action=='close'){
                    RabbitMq::getInstance()->closeQueue($queueName);
                }else{
                    $callback = $config['queue'][$queueName];
                    if(!class_exists($callback[0])){
                        throw new IndexException(4020,$callback[0].' 该类不存在');
                    }
                    $callback[0] = Container::get($callback[0]);
                    RabbitMq::getInstance()->receiveQueue($queueName,$callback);
                }

            }
            return self::SUCCESS;
        }catch (\Throwable $e){
            return self::FAILURE;
        }

    }


}
